/**
 * 56. 合并区间
 * https://leetcode-cn.com/problems/merge-intervals/
 */
const { displayNestedArray } = require('../../libs/public');

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
function merge(intervals) {
  intervals.sort((a, b) => a[0] - b[0]);
  const result = [];
  let i = 0;
  const last = intervals.length - 1;
  while (i < last) {
    const cur = intervals[i];
    const next = intervals[i + 1];
    if (cur[1] >= next[0]) {
      next[1] = Math.max(cur[1], next[1]);
      [next[0]] = cur;
    } else {
      result.push(cur);
    }
    i += 1;
  }
  result.push(intervals[last]);
  return result;
}

console.log(displayNestedArray(merge([[1, 3], [2, 6], [8, 10], [15, 18]])) === '[[1,6],[8,10],[15,18]]');
console.log(displayNestedArray(merge([[1, 4], [4, 5]])) === '[[1,5]]');
console.log(displayNestedArray(merge([[1, 4]])) === '[[1,4]]');
